import random

from flask import Blueprint
from flask_jwt_extended import verify_jwt_in_request
from sqlalchemy import text

from models import Article, db

article_api = Blueprint('article_api', __name__)

@article_api.before_request
def before_request():
    verify_jwt_in_request()

@article_api.route('/articleList', methods=['POST'])
def articleList():
    sql = text("""
        SELECT * FROM article order by rand() LIMIT 5
    """)
    results = db.session.execute(sql).fetchall()
    articles = []
    for res in results:
        aid = res[0]
        title = res[1]
        headpic = res[-2]
        abstract = res[-1]
        articles.append({
            'aid': aid,
            'title': title,
            'abstract': abstract,
            'headpic': headpic
        })
    return articles


@article_api.route('/<aid>', methods=['POST'])
def articleDetail(aid):
    article = Article.query.get(aid)
    info = {
        'headpic':article.headpic,
        'title': article.title,
        'body': article.body,
        'source': article.source,
        'source_href': article.source_href,
    }
    return info
